package com.zzf.concurrent.example.atomic;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author GaoFeng2017
 * @date 2019/9/12 16:49
 */
@Slf4j
public class AtomicBooleanTest {

    private AtomicBoolean atomicBoolean = new AtomicBoolean(false);


    @Test
    public void atomicBooleanTest() {
        AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        boolean isUpdate = atomicBoolean.compareAndSet(false, true);
        assertFalse(isUpdate);
    }

    @Test
    public void atomicBooleanTest2() {
        AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        boolean isUpdate = atomicBoolean.compareAndSet(true,false);
        assertTrue(isUpdate);
    }

    @Test
    public void atomicBooleanTest3() {

        new Thread(() -> {
            while (!atomicBoolean.get()) {
                log.info("flag is update.");
                TimeUtil.sleep(2000);
            }
        }).start();

        TimeUtil.sleep(6000);
        atomicBoolean.compareAndSet(false, true);
    }
}
